package com.lightsh.sensor;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;

public class ProximitySensor extends BaseSensor{

	private enum ProximityState{
		INIT,
		NEAR,
		FAR
	}
	
	private ProximityState mCurrentState = ProximityState.INIT;
	
	public ProximitySensor(Context context) {
		super(context);
	}

	@Override
	protected int getSensorType() {
		return Sensor.TYPE_PROXIMITY;
	}

	@Override
	protected String getLogTag() {
		return "ProximityController";
	}

	@Override
	protected void onSensorChanged(SensorEvent event) {
		float currentValue = event.values[0];
		ProximityState state = fetchState(event.sensor, currentValue);
		if(state != mCurrentState){
			final boolean isInit = mCurrentState == ProximityState.INIT;
			mCurrentState = state;
			if(!isInit){
				onProximityChanged(currentValue);
			}else{
				logW("init state = " + mCurrentState + ", value = " + currentValue);
			}
		}
	}
	
	private ProximityState fetchState(Sensor sensor, float currentValue){
		if(currentValue >= sensor.getMaximumRange()){
			return ProximityState.FAR;
		}else{
			return ProximityState.NEAR;
		}
	}
	private void onProximityChanged(float value){
		logD("proximity state change to " + mCurrentState + ", value = " + value);
		VibratorHelper.vibrate(mContext, 300);
	}
}
